package com.letoken.platform.pub.configuration;

import lombok.extern.log4j.Log4j2;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池的配置
 * 使用方式：直接使用@async注解标注在需要异步线程处理的方法上
 * 注意：@async方法不能和调用方在同一个类中，否则不生效
 */
@Log4j2
@Configuration
@EnableAsync
public class ThreadPoolConfiguration implements AsyncConfigurer {

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    /**
     * 重写自定义线程池配置
     *
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        // TODO Auto-generated method stub
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池数量，方法: 返回可用处理器的Java虚拟机的数量。
        executor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
        //最大线程数量
        executor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
        //线程池的队列容量
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        //线程名称的前缀
        executor.setThreadNamePrefix(threadPoolConfig.getThreadNamePrefix());
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 异步任务中异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
                log.error("execute Async error. methodName：{}", arg1.getName());
                log.error("execute Async error：{}. ----->> {}", arg0.getMessage(), arg0);
            }
        };
    }
}
